package libs

import (
	"io"
	"fmt"
	"path"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type AliyunOss struct {
	endpoint   string
	accessID   string
	accessKey  string
	bucketName string

	bucketClient *oss.Bucket
}

func NewAliyunOss() *AliyunOss {
	oss := &AliyunOss{
		endpoint:     "oss-cn-hangzhou.aliyuncs.com",
		accessID:     "LTAIG7npQLrXP9fp",
		accessKey:    "yFHRDeUWJmTIwZXv4AEn8TuHu2CnTa",
		bucketName:   "book-98nice",
		bucketClient: nil,
	}
	oss.initBucket()
	return oss
}

func (a *AliyunOss) UploadImage(key string, file io.Reader) bool {
	if a.bucketClient == nil {
		return false
	}
	if ext := path.Ext(key); ext != ".jpg" && ext != ".png" {
		return false
	}
	err := a.bucketClient.PutObject(key, file)
	if err != nil {
		fmt.Println("aliyun oss upload image error.", err, key)
		return false
	}
	return true
}

func (a *AliyunOss) initBucket() bool {
	client, err := oss.New(a.endpoint, a.accessID, a.accessKey)
	if err != nil {
		fmt.Println("aliyun oss new error.", err)
		return false
	}

	ossBucket, err := client.Bucket(a.bucketName)
	if err != nil {
		fmt.Println("aliyun oss init error.", err)
		return false
	}
	a.bucketClient = ossBucket
	return true
}
